
#import "HDSVTViewController.h"
#import "HDObtainBottomView.h"
#import "UILabel+HDMessage.h"
#import "HDWifiTool.h"
#import "Masonry.h"
#import "CustomIOSAlertView.h"
#import "HDSVTModel.h"
#import <MJExtension/MJExtension.h>
#import "HDBaseModel.h"
#import "HDJsonText.h"
#import "HDAlertTool.h"
#import "HDCheckLData.h"
#import "HDCheckBData.h"
@interface HDSVTViewController ()
@property (nonatomic,copy) NSString* wifiName;
@property(nonatomic,weak) UILabel* titleLabel;
@property(nonatomic,weak) UILabel* wifiLabel;
@property(nonatomic,strong) NSTimer* timer;
@property(nonatomic,weak) UITextView* textView;
@property(assign) CGFloat titleHeight;
@property(nonatomic,strong)NSMutableArray *levelArray;
@property(nonatomic,copy)NSString *jsonString;

@property(nonatomic,strong)NSDictionary *dict;
@end

@implementation HDSVTViewController
static NSString* wifiNameFix = @"Otis-";
-(void)viewDidLoad
{   self.title = @"从SVT获取数据";
    self.view.backgroundColor = [UIColor whiteColor];
    //获取wifi基础信息
    [self setWifiName];
    
    [self setSubviews];
    [self setBottomView];
    [self handleEventLog];
    
}
-(NSMutableArray *)levelArray
{
    if (!_levelArray) {
        _levelArray = [NSMutableArray array];
        for (int  i = 0; i < BaseLevel; i ++) {
            NSString *string = [NSString stringWithFormat:@"%d",i];
            [_levelArray addObject:string];
        }
    }
    return _levelArray;
}
/**
 创建底部的view
 */
-(void)setBottomView{
    
    HDObtainBottomView *obtain = [HDObtainBottomView instanceObtainBottomView];
    obtain.frame = CGRectMake(0,SCREEN_HEIGHT - 64 , SCREEN_WIDTH, 64);
    //开始的点击事件
    obtain.startBlock = ^(UIButton *btn){
        NSString* alertTitle;
        NSString* confirmStr;
        if ([self SSIDCheck]) {
            alertTitle = @"请在指定Wifi下操作";
            confirmStr = @"设置";
        }else{
            alertTitle = @"您确认从SVT获取数据吗？";
            confirmStr = @"确定";
        }
        
        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] initAlertDialogVieWithImageName:@""
                                                                                        dialogTitle:@"温馨提示"
                                                                                     dialogContents:alertTitle
                                                                                      dialogButtons:[NSMutableArray arrayWithObjects:confirmStr,@"取消", nil]];
        
        alertView.onButtonTouchUpInside = ^(CustomIOSAlertView *alertView, int buttonIndex){
            if (buttonIndex==0) {
                [alertView close];
                //confirmStr为确定时打开SVTAPP，否则跳转到设置界面链接指定wifi
                if ([confirmStr isEqualToString:@"确定"]) {
              
                    [self openSvtApp];
                }else{
                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }
            }else{
                [alertView close];
            }
        };
        [alertView show];
    
    };
//    //下一步的点击事件
//    for (UIButton *btn in obtain.subviews) {
//        btn.enabled = NO;
//    }
    obtain.nextBlock = ^(UIButton *btn){
         [[NSNotificationCenter defaultCenter]postNotificationName:HDNotificationPassValue object:self userInfo:self.dict];
       
        [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
    };
    
    [self.view addSubview:obtain];
}


/**
 UI子控件的布局
 */
-(void)setSubviews{
    UILabel* titleLabel=[[UILabel alloc] init];
    titleLabel.font=[UIFont systemFontOfSize:14.0];
    titleLabel.text=@"请连接到指定wifi网络";
    titleLabel.textColor=MDColor(37, 63, 96, 1.0);
    [self.view addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    UILabel* UnitNoLabel=[[UILabel alloc] init];
    UnitNoLabel.text=[NSString stringWithFormat:@"电梯编号                 ：%@",@"F8NVV498"];
    UnitNoLabel.textColor=MDColor(37, 63, 96, 1.0);
    [self.view addSubview:UnitNoLabel];
    
    UIView*lineView1=[[UIView alloc] init];
    lineView1.backgroundColor=MDDescriptionColor;
    [self.view addSubview:lineView1];
    
    UILabel* wifiLabel=[[UILabel alloc] init];
    wifiLabel.textColor=MDColor(37, 63, 96, 1.0);
    if (self.wifiName!=nil) {
        wifiLabel.text=[NSString stringWithFormat:@"当前所连接wifi名称：%@",self.wifiName];
    }else{
        wifiLabel.text=[NSString stringWithFormat:@"当前所连接wifi名称：请连接到指定wifi网络"];
    }
    [self.view addSubview:wifiLabel];
    self.wifiLabel = wifiLabel;
    
    UIView*lineView2=[[UIView alloc] init];
    lineView2.backgroundColor=MDDescriptionColor;
    [self.view addSubview:lineView2];
    
    UILabel* resultLabel=[[UILabel alloc] init];
    resultLabel.textColor=MDColor(37, 63, 96, 1.0);
    resultLabel.text=@"从SVT获取数据的结果 :";
    [self.view addSubview:resultLabel];
    
    UITextView* resultDetailLabel=[[UITextView alloc] init];
    resultDetailLabel.text=@"从SVT获取数据的结果 :";
    resultDetailLabel.layer.borderWidth=1.0;
    resultDetailLabel.font=[UIFont systemFontOfSize:16.0];
    resultDetailLabel.layer.borderColor=[UIColor lightGrayColor].CGColor;
    resultDetailLabel.editable=NO;
    [self.view addSubview:resultDetailLabel];
    self.textView=resultDetailLabel;
    
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(64);
        make.left.equalTo(self.view.mas_left).with.offset(20);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, self.titleHeight));
    }];
    
    [UnitNoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).with.offset(5);
        make.left.equalTo(titleLabel.mas_left).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 30));
    }];
    
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(UnitNoLabel.mas_bottom).with.offset(5);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 0.5));
    }];
    
    [wifiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView1.mas_bottom).with.offset(5);
        make.left.equalTo(titleLabel.mas_left).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 30));
    }];
    
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wifiLabel.mas_bottom).with.offset(5);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 0.5));
    }];
    
    [resultLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView2.mas_bottom).with.offset(5);
        make.left.equalTo(titleLabel.mas_left).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 30));
    }];
    
    [resultDetailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(resultLabel.mas_bottom).with.offset(5);
        make.left.equalTo(titleLabel.mas_left).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-40, 200));
    }];
    
    
    UIView* boomView=[[UIView alloc] init];
    boomView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:boomView];
    
    UIView* lineView=[[UIView alloc] init];
    lineView.backgroundColor=MDDescriptionColor;
    [boomView addSubview:lineView];
    
    [boomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.height.mas_equalTo(60);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(boomView.mas_left).with.offset(0);
        make.right.equalTo(boomView.mas_right).with.offset(0);
        make.top.equalTo(boomView.mas_top).with.offset(0);
        make.height.mas_equalTo(0.5);
    }];
    
    
}

/**
 懒加载初始化一个定时器 每隔2秒调以下timerfunc方法

 @return 返回这个NSTimer*对象
 */
-(NSTimer*)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timerfunc) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(void)timerfunc{
    NSDictionary* wifiDic =[HDWifiTool SSIDInfo];
    self.wifiName=wifiDic[@"SSID"];
    if (![self.wifiName hasPrefix:wifiNameFix]) {
        
        self.titleHeight=30;
        if (wifiDic[@"SSID"] == nil) {
            self.wifiLabel.text = [NSString stringWithFormat:@"当前所连接wifi名称：%@",@"请连接到指定wifi"];
        }else{
            self.wifiLabel.text = [NSString stringWithFormat:@"当前所连接wifi名称：%@",self.wifiName];
        }
        [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, self.titleHeight));
            
        }];
    }else{
        self.titleHeight=0;
        self.wifiLabel.text = [NSString stringWithFormat:@"当前所连接wifi名称：%@",self.wifiName];
        [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, self.titleHeight));
        }];
    }
}
//开始定时器
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.timer fire];
    
    
    
}
//关闭定时器
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self clearTimer];
    
}

-(void)clearTimer{
    [self.timer invalidate];
    self.timer=nil;
}

/**
 获取当前WIFI信息
 */
-(void)setWifiName{
    NSDictionary* wifiDic =[HDWifiTool SSIDInfo];
    self.wifiName=wifiDic[@"SSID"];
    if (self.wifiName==nil||[self.wifiName isEqualToString:@""]||![self.wifiName hasPrefix:wifiNameFix]) {
        self.titleHeight=30;
    }else{
        self.titleHeight=0;
    }
}
/**
 每次获取失败都需对WIFI进行检查
 
 @return 如果没有检查到WIFI则返回YES，如果有则返回NO
 */
-(BOOL)SSIDCheck{
    NSDictionary* wifiDic =[HDWifiTool SSIDInfo];
    NSString *SSID =wifiDic[@"SSID"];
    if (SSID ==nil||[SSID isEqualToString:@""]||![SSID hasPrefix:wifiNameFix]) {
        
        return YES;
    }
    return NO;
    
}

/**
 打开SVT
 */
-(void)openSvtApp{
    
    NSURL *appBUrl = [NSURL URLWithString:[NSString stringWithFormat:@"SVTApp://callType=MDApp&elevCode=%@",@"F8NVV497"]];
    // 2.判断手机中是否安装了对应程序
    if ([[UIApplication sharedApplication] canOpenURL:appBUrl]) {
        // 3. 打开应用程序App-B
        BOOL result = [[UIApplication sharedApplication] openURL:appBUrl];
        
        if (result) {
            //4.打开SVTAPP成功时纪录打开SVTAPP的时间
           
        }
        
    } else {
        CustomIOSAlertView* alertView2=[[CustomIOSAlertView alloc] initAlertDialogVieWithImageName:nil dialogTitle:@"温馨提示" dialogContents:@"没有安装指定App" dialogButtons:[NSMutableArray arrayWithObjects:@"确定", nil]];
        alertView2.onButtonTouchUpInside = ^(CustomIOSAlertView *alertView2, int buttonIndex){
            [alertView2 close];
        };
        [alertView2 show];
    }

 
}



/**
 从SVT返回到MD会回调这个方法，并把Eventlog传过来
 */
-(void)handleEventLog{
    WEAKSELF
    self.backBlcok = ^(){
        
        //将解码以后的值直接赋值给textView
        weakSelf.textView.layoutManager.allowsNonContiguousLayout = NO;
        weakSelf.textView.text=weakSelf.backString;
        NSString* tempStr = @"";//弹出框的结果提示
        NSString* tempStr1 = @"";//弹出框的确认提
        // 截取所获取的结果字符串
        NSRange range =[weakSelf.backString rangeOfString:@"MDApp://callType=SVTApp&eventLog="];
        NSString* jsonStr = [weakSelf.backString substringFromIndex:range.length+range.location];
       
        [weakSelf analysisSVTjson:jsonStr];
        
        
    };
    
}

/**
 解析SVT返回的json
 */
-(void)analysisSVTjson:(NSString *)jsonStr{
    NSData * jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSMutableArray *fooltArray = [NSMutableArray array];
   
    HDSVTModel* model =[HDSVTModel mj_objectWithKeyValues:dic[@"SVT"]];
    for (int i = 0; i < model.Drive.LData.L.count; i++) {
        L *l = model.Drive.LData.L[i];
        [fooltArray addObject:l.L];
        
    }
    
    //检查IsEventLogComplete是否都为True
    if ([model.Controller.IsEventLogComplete isEqualToString:@"True"] && [model.Drive.IsEventLogComplete isEqualToString:@"True"] ) {
       
    }else{
        //否则弹框，重新获取
        [HDAlertTool alertMessage:@"温馨提示" content:@"数据不完整，需要重新下载" buttonTitle:@"确定"];
        // return;
    }
    
    
    //检查LData和BData是否都存在
    if (model.Drive.LData && model.Drive.BData) {
        
        
    }else{
        //否则弹框，重新获取
        [HDAlertTool alertMessage:@"温馨提示" content:@"数据不完整，需要重新下载" buttonTitle:@"确定"];
       // return;
    }
    
    
    //检查服务端给的楼层是否和Ldata的楼层相等
    if ([HDCheckLData levelCompreFoolt:fooltArray level:self.levelArray] && [HDCheckLData LdataJsonCheck:model.Drive.LData]) {
        
        
    }else{
        //否则弹框，重新获取
        [HDAlertTool alertMessage:@"温馨提示" content:@"提示LData层站数不正确" buttonTitle:@"确定"];
        //return;
    }
    
    
     //检查Drive里的BData里是否有Current_info和Up，Down
    if (model.Drive.BData.Current_info && model.Drive.BData.Up && model.Drive.BData.Down && [HDCheckBData bdata1AttributeIsTrueOrFlase:model.Drive.BData]) {
        
        
    }else{
        //否则弹框，重新获取
        [HDAlertTool alertMessage:@"温馨提示" content:@"提示BData不正确1" buttonTitle:@"确定"];
       // return;
       
    }
    
    
    
    //检查Drive里的BData里是否有BL_BS和BD_BS，BL_CR,BD_CR
    if (model.Drive.BData.BL_BS && model.Drive.BData.BD_BS && model.Drive.BData.BL_CR && model.Drive.BData.BD_CR && [HDCheckBData bdata2AttributeIsTrueOrFlase:model.Drive.BData]) {
        
        
    }else{
        //否则弹框，重新获取
        [HDAlertTool alertMessage:@"温馨提示" content:@"提示BData不正确2" buttonTitle:@"确定"];
       // return;
        
    }
    
    //将baseModel转为Json
     NSString *jsonText =  [HDJsonText modelToJsonWithSVT:model];
     NSDictionary *dict = @{@"passValue" : jsonText};
      self.dict = dict;
     NSLog(@"%@",dict);
}

-(void)dealloc{

    self.wifiName = nil;
    [self clearTimer];
    
}

//
@end
